<template>
  <div class="product-list">
    <h1>商品信息</h1>
    <div class="action-bar">
      <el-button type="primary" @click="dialogVisible=true">添加商品</el-button>
    </div>
    <el-table :data="products" style="width: 100%" stripe>
      <el-table-column prop="storeProductId" label="ID" width="100" />
      <el-table-column prop="productName" label="名称" width="180" />
      <el-table-column prop="price" label="价格" width="180" />
      <el-table-column prop="discount" label="价格折扣" width="180">
        <template #default="scope">
          {{ scope.row.discount==1?'没有折扣':scope.row.discount*10+"折"}}
        </template>
      </el-table-column>
      <el-table-column prop="foodTypeName" label="菜品类型" width="180" />
      <el-table-column prop="storeProductState" label="是否下架" width="180">
        <template #default="scope">
          {{ scope.row.storeProductState == 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-size="searchParam.pageSize"
          :current-page="searchParam.pageNum"
          :page-sizes="[2, 3, 5, 10]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="添加商品" v-model="dialogVisible" width="50%">
      <el-form :model="newProduct" label-width="100px" :rules="rules" ref="productForm">
        <el-form-item label="菜品名称" prop="productName">
          <el-input v-model="newProduct.productName" placeholder="请输入菜品名称"></el-input>
        </el-form-item>
        <el-form-item label="菜品介绍" prop="productIntr">
          <el-input v-model="newProduct.productIntr" type="textarea" placeholder="请输入菜品介绍"></el-input>
        </el-form-item>
        <el-form-item label="菜品类型" prop="food_type_id">
          <el-select v-model="newProduct.food_type_id" placeholder="请选择菜品类型">
            <el-option v-for="type in foodTypes" :key="type.foodTypeId" :label="type.foodTypeName" :value="type.foodTypeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品价格" prop="productPrice">
          <el-input v-model="newProduct.productPrice" placeholder="请输入菜品价格">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="file">
          <el-upload
            
            :on-change="handleFileChange"
            :auto-upload="false"
            accept="image/*"
            :limit="1"
          >
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" style="position: relative;left: -600px;">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情模态框 -->
    <el-dialog
        v-model="detailVisible"
        title="商品详情"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <div class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">
            <span class="detail-value">{{ currentProduct.storeProductId }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="名称">
            <span class="detail-value">{{ currentProduct.productName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            <span class="detail-value">{{ currentProduct.price }} 元</span>
          </el-descriptions-item>
          <el-descriptions-item label="价格折扣">
            <span class="detail-value">{{ currentProduct.discount }} 折</span>
          </el-descriptions-item>
          <el-descriptions-item label="菜品类型">
            <span class="detail-value">{{ currentProduct.foodTypeName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="是否下架">
            <span class="detail-value">{{ currentProduct.storeProductState == 1 ? '是' : '否' }}</span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="image-section">
          <h3>商品图片</h3>
          <el-image
              v-if="currentProduct.filePath"
              :src="currentProduct.filePath"
              :preview-src-list="[currentProduct.filePath]"
              fit="cover"
              style="width: 100%; max-height: 300px; border-radius: 8px;"
          />
          <el-empty v-else description="暂无图片" />
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailVisible = false" style="position: relative;left: -800px;" >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElInput, ElButton, ElTable, ElTableColumn, ElPagination, ElDialog, ElForm, ElFormItem, ElSwitch,ElMessage } from 'element-plus';
import axios from 'axios';
export default {
  components: {
    ElInput,
    ElButton,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElDialog,
    ElForm,
    ElFormItem,
    ElSwitch,
  },
  data() {
    return {
      products: [],
      searchParam: {
        storeId: localStorage.getItem("storeId"),
        pageNum: 1,
        pageSize: 5
      },
      foodTypes: [], // 食物类型列表
      total: 0,
      detailVisible: false, // 控制模态框显示
      currentProduct: {},
      fileUpload:null,
      dialogVisible: false,
      newProduct: {
      },
      rules: {
        dishName: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        dishDesc: [
          { required: true, message: '请输入菜品介绍', trigger: 'blur' }
        ],
        dishType: [
          { required: true, message: '请选择菜品类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '价格必须是两位小数且大于0的数字', trigger: 'blur' }
        ],
      },
    };
  },
  methods:{

    addProduct() {
    this.uploadProductImg()
      this.$refs.productForm.validate(valid => {
        if (valid) {
          axios.post('/meals/storeProduct/addStoreProduct',this.newProduct).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('添加成功');
              this.dialogVisible = false;
              this.newProduct = {};
              this.fileUpload = null;
              this.getProducts();
            } else {
              ElMessage.error(res.data.msg);
            }
          });
        } else {
          ElMessage.warning('请填写必填项并确保格式正确');
          return false;
        }
      });
    },
    uploadProductImg(){
        const formData = new FormData();
        formData.append('file', this.fileUpload);
        axios.post('/meals/storeFileUpload/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.data.code === 200) {
            ElMessage.success('上传成功');
            this.newProduct.filePath = res.data.data;
            console.log(res.data.data);
          } else {
            ElMessage.error(res.data.msg);
          }
        })
    },
    handleFileChange(file) {
      this.fileUpload = file.raw;
    },
    getProducts() {
      axios.post('/meals/storeProduct/searchStoreProductList', this.searchParam).then(res => {
        if (res.data.code === 200) {
          this.products = res.data.data.list;
          this.total = res.data.data.total;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    },
    getFoodTypes() {
      axios.get('/meals/foodType/searchType', {
        params: {storeId: localStorage.getItem("storeId")}
      }).then(res => {
        if (res.data.code === 200) {
          this.foodTypes = res.data.data;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    },
    showDetail(product) {
      this.currentProduct = product; // 设置当前商品详情
      this.detailVisible = true; // 显示模态框
    },

    handleSizeChange(newSize) {
      this.searchParam.pageSize = newSize;
      this.searchParam.pageNum = 1; // 重置到第一页
      this.getProducts();
    },
    handleCurrentChange(newPage) {
      this.searchParam.pageNum = newPage;
      this.getProducts();
    },
  },
  created() {
    this.getProducts();
    this.getFoodTypes();
  }
};
</script>

<style scoped>
.product-list {
  margin: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
}

.el-dialog__footer .el-button {
  margin-left: 10px;
}
</style>